package com.hifar.test.task.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.constant.SystemConsts;
import com.hifar.fw.json.JsonUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.model.VO.IdVO;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.SystemUtil;
import com.hifar.test.entrust.constant.TaskConsts;
import com.hifar.test.entrust.constant.TestConsts;
import com.hifar.test.entrust.pojo.HfEnvGkEntrust;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.task.pojo.HfEnvTask;
import com.hifar.test.task.pojo.VO.*;
import com.hifar.test.task.service.IHfEnvTaskService;
import com.hifar.test.test.pojo.HfEnvTest;
import com.hifar.test.test.pojo.VO.UploadFileVO;
import com.hifar.test.test.service.IHfEnvTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author zhuWeiWei
 * @description TODO
 * @date 2025/5/27 15:36
 */
@RestController
@RequestMapping("/api/busi/test/envTask")
@Api(tags = "试验任务功能")
public class HfEnvTaskController {

    @Autowired
    private IHfEnvTaskService taskService;
    @Autowired
    private IHfEnvTestService testService;
    @Autowired
    private IHfEnvGkEntrustService gkEntrustService;


    @PostMapping("/listPage")
    @ApiOperation("任务规划-列表查询")
    public BusiResponse listPage(@RequestBody @Validated TaskQueryParamsVO queryParamsVO) {
        QueryParamBean<HfEnvTask> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvTask.class, "t");
        Page<HfEnvTask> page = queryParamBean.getPage();
        QueryWrapper<HfEnvTask> queryWrapper = queryParamBean.getQueryWrapper();
        String entrustId = queryParamsVO.getEntrustId();
        String finishFlag = queryParamsVO.getFinishFlag();
        String cancelFlag = queryParamsVO.getCancelFlag();
        if (Objects.equals(SystemConsts.NO, finishFlag)) {
            queryWrapper.ne("t.status", TaskConsts.TASK_STATUS_FINISH);
        }
        if (Objects.equals(SystemConsts.NO, cancelFlag)) {
            queryWrapper.ne("t.status", TaskConsts.TASK_STATUS_YQX);
        }
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(entrustId), HfEnvTask::getGkEntrustId, entrustId);
        queryWrapper.lambda()
                .orderByDesc(HfEnvTask::getCreateTime);
        Page<HfEnvTaskVO> pageData = taskService.pageVO(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping("/cancel")
    @ApiOperation("任务规划-取消")
    public BusiResponse cancel(@RequestBody @Validated HfEnvTaskCancelSaveVO taskCancelVO) {
        taskService.cancel(taskCancelVO);
        return BusiResponse.OK();
    }

    @ApiOperation("查询任务取消详情")
    @GetMapping("/queryCancelById")
    public BusiResponse queryCancelById(@RequestParam("id") String id) {
        HfEnvTaskCancelVO taskCancelVO = taskService.queryCancelById(id);
        return BusiResponse.OK(taskCancelVO);
    }


    @PostMapping("/addTest")
    @ApiOperation("任务规划-分配设备")
    public BusiResponse addTest(@RequestBody @Validated AddTestVO addTestVO) {
        taskService.addTest(addTestVO);
        return BusiResponse.OK();
    }

    @PostMapping("/taskMatchEquipList")
    @ApiOperation("任务规划-分配设备甘特图")
    public BusiResponse taskMatchEquipList(@RequestBody @Validated TaskMatchEquipQueryVO matchEquipQueryVO) {
        TaskMatchAndNumDTO taskMatchAndNumDTO = taskService.taskMatchEquipList(matchEquipQueryVO);
        List<TaskMatchEquipVO> taskMatchEquipVOList = Optional.ofNullable(taskMatchAndNumDTO.getTaskMatchEquipVOList())
                .orElse(new ArrayList<>());
        TestStatusNumVO numVO = Optional.ofNullable(taskMatchAndNumDTO.getNumVO()).orElse(new TestStatusNumVO());
        BusiResponse<List<TaskMatchEquipVO>> response = BusiResponse.OK(taskMatchEquipVOList);
        response.setExt(JsonUtils.toMap(JsonUtils.toJson(numVO)));
        return response;
    }


    @GetMapping("/listPendingEntrust")
    @ApiOperation("任务规划-委托列表")
    public BusiResponse listPendingEntrust(@RequestParam("entrustCode") String entrustCode) {
        QueryWrapper<HfEnvGkEntrust> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .like(Objects.nonNull(entrustCode), "e.entrust_code", entrustCode);

        List<TaskPendingEntrustVO> taskPendingEntrustVOList = taskService.listPendingEntrust(queryWrapper);
        return BusiResponse.OK(taskPendingEntrustVOList);
    }


    @PostMapping("/listPageForTask")
    @ApiOperation("查询任务下试验")
    public BusiResponse listPageForTask(@RequestBody @Validated HfEnvTaskTestQueryParamVO queryParamsVO) {
        QueryParamBean<HfEnvTest> testQueryParamBean = new QueryParamBean<>(queryParamsVO);
        testQueryParamBean.addColumns(HfEnvTest.class, "t");
        String taskId = queryParamsVO.getTaskId();
        QueryWrapper<HfEnvTest> queryWrapper = testQueryParamBean.getQueryWrapper();
        Page<HfEnvTest> page = testQueryParamBean.getPage();
        queryWrapper.apply(" exists (select 1 FROM hf_env_task task" +
                        " left join hf_env_task_test_relation tr ON task.id=tr.task_id " +
                        " where task.id={0} and tr.test_id=t.id and task.del_flag={1} and t.status !={2} )"
                , taskId, "0", TestConsts.TEST_STATUS_REVOKE);
        Page<HfEnvTaskTestVO> pageData = taskService.pageTest(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping("/equipTestBoard")
    @ApiOperation("试验总览")
    public BusiResponse equipTestBoard(@RequestBody @Validated EquipTestBoardQueryVO equipTestBoardQueryVO) {
//        List<TaskMatchEquipVO> taskMatchEquipVOList = taskService.equipTestBoardList(equipTestBoardQueryVO);
        TaskMatchAndNumDTO taskMatchAndNumDTO = taskService.equipTestBoardList(equipTestBoardQueryVO);
        List<TaskMatchEquipVO> taskMatchEquipVOList = Optional.ofNullable(taskMatchAndNumDTO.getTaskMatchEquipVOList())
                .orElse(new ArrayList<>());
        TestStatusNumVO numVO = Optional.ofNullable(taskMatchAndNumDTO.getNumVO()).orElse(new TestStatusNumVO());
        BusiResponse<List<TaskMatchEquipVO>> response = BusiResponse.OK(taskMatchEquipVOList);
        response.setExt(JsonUtils.toMap(JsonUtils.toJson(numVO)));
        return response;
    }


    @PostMapping("/deleteById")
    @ApiOperation("删除任务")
    public BusiResponse deleteById(@RequestBody @Validated IdVO idVO) {

        HfEnvTask hfEnvTask = taskService.getById(idVO.getId());
        Assert.notNull(hfEnvTask, "任务数据不存在!");
        taskService.deleteById(idVO.getId());

        String gkEntrustId = hfEnvTask.getGkEntrustId();

        List<HfEnvTask> taskList = taskService.listByEntrustId(gkEntrustId);
        if (taskList.isEmpty()) {
            gkEntrustService.removeById(gkEntrustId);
        }
        return BusiResponse.OK();
    }


    @PostMapping("/queryListPage")
    @ApiOperation("任务查询-列表查询")
    public BusiResponse queryListPage(@RequestBody @Validated TaskQueryParamsVO queryParamsVO) {
        QueryParamBean<HfEnvTask> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvTask.class, "t");
        Page<HfEnvTask> page = queryParamBean.getPage();
        QueryWrapper<HfEnvTask> queryWrapper = queryParamBean.getQueryWrapper();
        String entrustId = queryParamsVO.getEntrustId();
        String finishFlag = queryParamsVO.getFinishFlag();
        String cancelFlag = queryParamsVO.getCancelFlag();
        if (Objects.equals(SystemConsts.NO, finishFlag)) {
            queryWrapper.ne("t.status", TaskConsts.TASK_STATUS_FINISH);
        }
        if (Objects.equals(SystemConsts.NO, cancelFlag)) {
            queryWrapper.ne("t.status", TaskConsts.TASK_STATUS_YQX);
        }
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(entrustId), HfEnvTask::getGkEntrustId, entrustId);
        queryWrapper.lambda()
                .orderByDesc(HfEnvTask::getCreateTime);
        Page<HfEnvTaskVO> pageData = taskService.pageVO(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @ApiOperation("任务查询-生成原始记录")
    @PostMapping("/generateProcessRecord")
    public BusiResponse generateProcessRecord(@RequestBody @Validated IdVO idVO) {
        taskService.generateProcessRecord(idVO.getId());
        return BusiResponse.OK();
    }


    @ApiOperation("任务查询-替换任务原始记录")
    @PostMapping("/replaceTestReport")
    public BusiResponse replaceTestReport(@RequestBody @Validated UploadFileVO uploadFileVO) {
        taskService.replaceTestReport(uploadFileVO.getId(), uploadFileVO.getFileId());
        return BusiResponse.OK();
    }


    @ApiOperation("任务查询-删除任务原始记录")
    @PostMapping("/delTestReport")
    public BusiResponse delTestReport(@RequestBody @Validated IdVO idVO) {
        taskService.delTestReport(idVO.getId());
        return BusiResponse.OK();
    }
}
